# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 角色管理
"""
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated

from dvadmin.system.models import Role, Menu
from dvadmin.system.views.dept import DeptSerializer
# from dvadmin.system.views.menu import MenuSerializer
# from dvadmin.system.views.menu_button import MenuButtonSerializer
from dvadmin.system.views.devicetypes import DeviceTypesSerializer
from dvadmin.system.views.menu import MenuSerializer
from dvadmin.system.views.roadsinfos import RoadsinfosSerializer
from dvadmin.system.views.structures import StructuresSerializer
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.validator import CustomUniqueValidator
from dvadmin.utils.viewset import CustomModelViewSet


class BaseRoleSerializer(CustomModelSerializer):
    """
    角色-序列化器
    """

    class Meta:
        model = Role
        fields = ['id', 'name', 'key', 'sort', 'status', 'admin', 'data_range', ]
        read_only_fields = ["id"]


class RoleSerializer(CustomModelSerializer):
    """
    角色-序列化器
    """

    class Meta:
        model = Role
        fields = '__all__'
        read_only_fields = ["id"]


class RoleCreateUpdateSerializer(CustomModelSerializer):
    """
    角色管理 创建/更新时的列化器
    """
    menu = MenuSerializer(many=True, read_only=True)
    dept = DeptSerializer(many=True, read_only=True)
    road = RoadsinfosSerializer(many=True, read_only=True)
    structure = StructuresSerializer(many=True, read_only=True)
    device_type = DeviceTypesSerializer(many=True, read_only=True)
    # permission = MenuButtonSerializer(many=True, read_only=True)
    key = serializers.CharField(max_length=50,
                                validators=[CustomUniqueValidator(queryset=Role.objects.all(), message="权限字符必须唯一")])
    name = serializers.CharField(max_length=50, validators=[CustomUniqueValidator(queryset=Role.objects.all())])

    def validate(self, attrs: dict):
        return super().validate(attrs)

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.dept.set(self.initial_data.get('dept', []))
        data.menu.set(self.initial_data.get('menu', []))
        data.road.set(self.initial_data.get('road', []))
        data.structure.set(self.initial_data.get('structure', []))
        data.device_type.set(self.initial_data.get('device_type', []))
        # data.permission.set(self.initial_data.get('permission', []))
        return data

    class Meta:
        model = Role
        fields = '__all__'


class MenuPermissonSerializer(CustomModelSerializer):
    """
    菜单的按钮权限
    """

    # menuPermission = MenuButtonSerializer(many=True, read_only=True)

    class Meta:
        model = Menu
        fields = '__all__'


class RoleViewSet(CustomModelViewSet):
    """
    角色管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    permission_classes = [IsAuthenticated]
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    create_serializer_class = RoleCreateUpdateSerializer
    update_serializer_class = RoleCreateUpdateSerializer

    def roleId_to_menu(self, request, *args, **kwargs):
        """通过角色id获取该角色用于的菜单"""
        # instance = self.get_object()
        # queryset = instance.menu.all()
        queryset = Menu.objects.filter(status=1).all()
        serializer = MenuPermissonSerializer(queryset, many=True)
        return SuccessResponse(data=serializer.data)

    def role_data(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = RoleSerializer(instance)
        return SuccessResponse(data=serializer.data)


def get_user_role_extand_info(role_ids):
    # 获取用户角色扩展信息
    data = {}
    roads = []
    depts = []
    menus = []
    structure = []
    device_type = []
    for role_id in role_ids:
        # 获取角色信息
        role = Role.objects.get(id=role_id)
        roads.extend(role.road.values_list('id', flat=True))
        depts.extend(role.dept.values_list('id', flat=True))
        menus.extend(role.menu.values_list('id', flat=True))
        structure.extend(role.structure.values_list('id', flat=True))
        device_type.extend(role.device_type.values_list('id', flat=True))

    roads = list(set(roads))
    depts = list(set(depts))
    menus = list(set(menus))
    structure = list(set(structure))
    device_type = list(set(device_type))

    data = dict(road=roads, dept=depts, menu=menus, structure=structure, device_type=device_type)

    return data
